import aes from 'crypto-js/aes'
import encUtf8 from 'crypto-js/enc-utf8'
import { debounce } from 'lodash'
import QueryString from 'qs'

/** 加密的密钥 */
export const CRYPTOJSKEY = ''

/**
 * AES加密
 * @param {string} plaintText 需加密的文本
 * @return {string} 加密文本
 */
export function encrypt (plaintText: string) {
  const key = encUtf8.parse(CRYPTOJSKEY)
  const word = encUtf8.parse(plaintText)
  const encryptedData = aes.encrypt(word, key, { iv: key })
  return encryptedData.toString()
}

/**
 * AES解密
 * @param {string} test 需解密的文本
 * @return {string} 解密文本
 */
export function decrypt (text: string) {
  const key = encUtf8.parse(CRYPTOJSKEY)
  return aes.decrypt(text, key, { iv: key }).toString(encUtf8)
}

/**
 * 获取H5的运行环境
 * @return {object} isWx: 是否微信, isWxWork: 是否企微, isWxMiniprogram: 是否小程序, isMobile: 是否手机
 */
export function getH5Env () {
  if (!navigator) {
    console.warn('非h5环境请不要使用！')
    return {}
  }
  const ua = navigator.userAgent.toLowerCase()

  return {
    isWx: ua.indexOf('micromessenger') > -1,
    isWxWork: ua.indexOf('wxwork') > -1,
    isWxMiniprogram: ua.indexOf('miniprogram') > -1,
    isMobile: ua.indexOf('mobile') > -1,
  }
}
/**
 * 获取当前页面路径
 * @description 注意执行时机
 * @return {string}
 */
export function getCurrentPath () {
  const pages = getCurrentPages()
  if (pages.length === 0) return ''
  // @ts-ignore @dcloudio/types缺少对options定义
  const { options, route } = pages[pages.length - 1]
  if (!options) return route
  const routeParams = Object.entries(options).reduce((arr, item, index) => {
    const [key, value] = item
    const params = index === 0 ? `?${key}=${value}` : `&${key}=${value}`
    return arr + params
  }, '')
  return '/' + route + routeParams
}

/**
 * 页面跳转
 * @description 页面跳转方式统一封装
 * @example
 * ```js
 * // 跳转外部小程序（仅支持微信小程序）
 * goPage({
 *  url: 'wxxxxxxxxx,/pages/index'
 * })
 * // 跳转h5页
 * goPage({
 *  url: 'https://ideamake.cn'
 * })
 * ```
 * ...
 * @see navigateTo: http://uniapp.dcloud.io/api/router?id=navigateto
 * @see redirectTo: http://uniapp.dcloud.io/api/router?id=redirectto
 * @see reLaunch: http://uniapp.dcloud.io/api/router?id=relaunch
 * @see switchTab: http://uniapp.dcloud.io/api/router?id=switchtab
 * @param {GoPageOptions} { url, params, type = 'navigateTo', success, fail, complete }
 */

type ExtendGoPageOption = {
  params?: object,
  type?: 'navigateTo' | 'redirectTo' | 'reLaunch' | 'switchTab',
}
type GoPageOptions = UniApp.NavigateToOptions & UniApp.ReLaunchOptions & UniApp.RedirectToOptions & UniApp.SwitchTabOptions & ExtendGoPageOption

export const goPage = debounce(({ url, params, type = 'navigateTo', success, fail, complete, ...arg }: GoPageOptions) => {
  const urlParams = params ? QueryString.stringify(params) : ''
  const appIdRule = /^wx(?=.*\d)(?=.*[a-z])[\da-z]{16}$/

  const urlParamsHandler = (path: string, params: string) => {
    if (params) {
      return path.includes('?') ? `${path}&${urlParams}` : `${path}?${urlParams}`
    } else {
      return path
    }
  }

  // #ifdef MP-WEIXIN
  // 跳转外部小程序
  // 应用场景：pc端配置的跳转规则
  if (url.includes(',') && appIdRule.test(url.split(',')[0])) {
    const [appId, path] = url.split(',')
    uni.navigateToMiniProgram({ appId, path: urlParamsHandler(path, urlParams) })
    return
  }
  // #endif

  // 跳转h5页
  // 应用场景：pc端配置的跳转规则
  if (url.indexOf('https') === 0) {
    url = `/pages/common/webview/index?url=${encodeURIComponent(url as string)}`
  }

  // #ifdef MP-WEIXIN
  if (url.includes('plugin-private')) { // 跳转小程序插件页
    url = urlParamsHandler(url as string, urlParams)
    return
  }
  // #endif

  url = urlParamsHandler(url.replace(/^\/?pages\//, '/pages/'), urlParams)

  const navigatorOption: UniApp.NavigateToOptions = {
    url,
    ...arg,
  }
  if (success) navigatorOption.success = success
  if (fail) navigatorOption.fail = fail
  if (complete) navigatorOption.complete = complete

  uni[type](navigatorOption) // TIP: 动态调用，摇树无法识别
}, 0)

/**
 * 延时方法
 * @param {Number} time 毫秒
 * @returns {Promise}
 */
export const sleep = (time = 1000) => {
  return new Promise(resolve => setTimeout(resolve, time))
}
